package com.guoyihao.oj.judge.strategy.Impl;

import cn.hutool.json.JSONUtil;
import com.guoyihao.oj.judge.strategy.JudgeContext;
import com.guoyihao.oj.judge.strategy.JudgeStrategy;
import com.guoyihao.oj.model.dto.question.JudgeCase;
import com.guoyihao.oj.model.dto.question.JudgeConfig;
import com.guoyihao.oj.model.dto.questionsubmit.JudgeInfo;
import com.guoyihao.oj.model.entity.Question;
import com.guoyihao.oj.model.entity.QuestionSubmit;
import com.guoyihao.oj.model.enums.JudgeInfoMessageEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Java语言的判题策略
 */
@Slf4j
public class JavaLanguageJudgeStrategy implements JudgeStrategy {
    /**
     * 判题
     * @param judgeContext
     * @return
     */
    @Override
    public JudgeInfo doJudge(JudgeContext judgeContext) {
        //获取判题上下文的参数
        JudgeInfo judgeInfo = judgeContext.getJudgeInfo();
        long time  = judgeInfo.getTime();
        Long memory = judgeInfo.getMemory();
        List<JudgeCase> judgeCaseList = judgeContext.getJudgeCaseList();
        List<String> inputList = judgeContext.getInputList();
        List<String> outputList = judgeContext.getOutputList();
        Question question = judgeContext.getQuestion();
        QuestionSubmit questionSubmit = judgeContext.getQuestionSubmit();
        JudgeInfo judgeInfoResponse = new JudgeInfo();
        judgeInfoResponse.setMemory(memory);
        judgeInfoResponse.setTime(time);
        // 先判断沙箱的执行结果输出数量是否和预期输入数量一致
        if(outputList.size() != inputList.size()){
            String message = JudgeInfoMessageEnum.WRONG_ANSWER.getValue();
            judgeInfoResponse.setMessage(message);
            return judgeInfoResponse;
        }
        //判断正确答案的输出用例是否和用户执行代码后所取得的输出用例是否一致
        for(int i = 0; i < judgeCaseList.size() ; i++){
            log.info("结果：{}，原测试样例结果：{}",outputList.get(i).trim(),judgeCaseList.get(i).getOutput().trim());
            if(!outputList.get(i).trim().equals(judgeCaseList.get(i).getOutput().trim())){
                String message = JudgeInfoMessageEnum.WRONG_ANSWER.getValue();
                judgeInfoResponse.setMessage(message);
                return judgeInfoResponse;
            }
        }
        //判断题目限制
        JudgeConfig judgeConfig = JSONUtil.toBean(question.getJudgeConfig(), JudgeConfig.class);
        Long needMemoryLimit = judgeConfig.getMemoryLimit();
        Long needTimeLimit = judgeConfig.getTimeLimit();
        if(memory > needMemoryLimit || time > needTimeLimit){
            String message = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED.getValue();
            judgeInfoResponse.setMessage(message);
            return judgeInfoResponse;
        }
        judgeInfoResponse.setMessage(JudgeInfoMessageEnum.ACCEPTED.getValue());
        return judgeInfoResponse;
    }
}
